using BW.MesProject.BasicData.Application;
using BW.MesProject.BasicData.Domain.基础;
using BW.MesProject.BasicData.Host;
using BW.MesProject.BasicData.Infrastructure;
using BW.MesProject.Public.Infrastructure;
using SqlSugar;
using Yitter.IdGenerator;
using ServiceManagement.Consul;
using Autofac;
using Autofac.Extensions.DependencyInjection;
using System.Linq;
using OfficeOpenXml;

/// <summary>
/// 基础数据微服务主程序
/// 配置依赖注入、数据库连接和中间件
/// </summary>

// 设置EPPlus许可证
ExcelPackage.License.SetNonCommercialOrganization("BW.MesProject");

// 配置Consul
var builder = WebApplication.CreateBuilder(args);
// 配置Consul
builder.Services.AddControllers().AddJsonOptions(a => a.JsonSerializerOptions.PropertyNamingPolicy = null);
// Add services to the container.

builder.Services.AddControllers();
// Learn more about configuring Swagger/OpenAPI at https://aka.ms/aspnetcore/swashbuckle
builder.Services.AddEndpointsApiExplorer();
// 配置Swagger文档
builder.Services.AddSwaggerGen(a =>
{
    var file = Path.Combine(AppContext.BaseDirectory + "BW.MesProject.BasicData.Host.xml");
    a.IncludeXmlComments(file, true);
    var fileapplication = Path.Combine(AppContext.BaseDirectory + "BW.MesProject.BasicData.Application.xml");
    a.IncludeXmlComments(fileapplication, true);
});

// 注册HttpClient工厂
builder.Services.AddHttpClient();

// 注册HttpContext访问器
builder.Services.AddHttpContextAccessor();
// SqlSugar 注册
builder.Services.AddSingleton<ISqlSugarClient>(sp =>
    new SqlSugarClient(new ConnectionConfig
    {
        ConnectionString = builder.Configuration.GetConnectionString("conn"),
        DbType = DbType.MySql,
        IsAutoCloseConnection = true
    }));
builder.Configuration.Register();


// 使用Autofac作为依赖注入容器
builder.Host.UseServiceProviderFactory(new AutofacServiceProviderFactory());
// 配置Autofac
builder.Host.ConfigureContainer<ContainerBuilder>(builder.ConfigureAutofac());

// 注册AutoMapper
builder.Services.AddAutoMapper(typeof(AutoMap));
// 配置雪花ID生成器
YitIdHelper.SetIdGenerator(new IdGeneratorOptions());

var app = builder.Build();
var db = app.Services.GetRequiredService<ISqlSugarClient>();
db.CodeFirst.InitTables<Bommodel>(); //所有库都支持
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
    app.UseSwagger();
    app.UseSwaggerUI();
}

app.UseAuthorization();

app.MapControllers();

app.Run();
